const moment = require('moment');
const WebSocket = require('ws');
const pako = require('pako');
const axios = require('axios');
// const WS_URL = 'wss://api.huobi.pro/ws';
// 此地址用于国内不翻墙调试
const WS_URL = 'wss://api.huobi.br.com/ws';

var orderbook = {};
var wss = require("nodejs-websocket");
console.log("开始建立连接...");
var game1 = null,game2 = null , game1Ready = false , game2Ready = false;

exports.OrderBook = orderbook;

function handle(data) {
    console.log('received', data.ch, 'data.ts', data.ts, 'crawler.ts', moment().format('x'));
    let symbol = data.ch.split('.')[1];
    let channel = data.ch.split('.')[2];
    switch (channel) {
        case 'depth':
            orderbook[symbol] = data.tick;
            console.log(data.tick);
            break;
        case 'kline':
            console.log('kline', data.tick);
            break;
    }
}

function subscribe(ws) {
    var symbols = ['btcusdt'];
    // 订阅深度
    // 谨慎选择合并的深度，ws每次推送全量的深度数据，若未能及时处理容易引起消息堆积并且引发行情延时
    // for (let symbol of symbols) {
    //     ws.send(JSON.stringify({
    //         "sub": `market.${symbol}.kline.1min`,
    //         "id": `${symbol}`,
    //         // "sub": `market.${symbol}.depth.step0`,
    //         // "id": `${symbol}`
    //     }));
    // }
    // 订阅K线
    for (let symbol of symbols) {
        ws.send(JSON.stringify({
            "sub": `market.${symbol}.kline.1min`,
            "id": `${symbol}`,
            // kline 的历史
            // "req": `market.${symbol}.kline.1min`,
            // "id": "id generated by client",
        }));
    }
}

function init() {
    var ws = new WebSocket(WS_URL);
    ws.on('open', () => {
        console.log('open');
        subscribe(ws);
    });
    ws.on('message', (data) => {
        let text = pako.inflate(data, {
            to: 'string'
        });
        let msg = JSON.parse(text);
        if (msg.ping) {
            console.log(msg);

            ws.send(JSON.stringify({
                pong: msg.ping
            }));
        } else if (msg.tick) {
            // console.log(msg);
            console.log(11111);
            // console.log(JSON.parse(msg.tick.id));
            console.log((msg));
            // handle(msg);
            console.log(2222);



            wss.createServer(function(conn){
                conn.on("text", function (str) {
                    console.log("收到的信息为:"+str)
                    if(str==="game1"){
                        game1 = conn;
                        game1Ready = true;
                        conn.sendText("success");
                    }
                    if(str==="game2"){
                        game2 = conn;
                        game2Ready = true;
                    }

                    if(game1Ready&&game2Ready){
                        game2.sendText("admin_admin");
                    }

                    conn.sendText(JSON.stringify(msg))
                })
                conn.on("close", function (code, reason) {
                    console.log("关闭连接")
                });
                conn.on("error", function (code, reason) {
                    console.log("异常关闭")
                });
            }).listen(9900)
            // console.log("WebSocket建立完毕")


            // let url = 'http://chen.test/api/admin/webs/chen';
            // axios.post(url, {
            //   message: JSON.stringify(msg),
            //   id: JSON.parse(msg.tick.id)
            // })
            // .then(function (response) {
            //   console.log(response);
            // })
            // .catch(function (error) {
            //   console.log(error);
            // });
            // console.log(111);

        } else {
            console.log(text);
        }
    });
    ws.on('close', () => {
        console.log('close');
        init();
    });
    ws.on('error', err => {
        console.log('error', err);
        init();
    });
}

init();
